﻿//  -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	Smart.Documents
//  File name:	LookupFieldWithPickerDialog.cs
//  Developer:	Solomatov Igor
//  Created:	16.04.2012
// 
//  -------------------- iSharePoint -------------------- //

using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

// ReSharper disable CheckNamespace

namespace Smart.Documents.Fields.LookupFieldWithPicker
// ReSharper restore CheckNamespace
{
	public class LookupFieldWithPickerDialog : PickerDialog
	{
		public LookupFieldWithPickerDialog()
			: base(new LookupFieldWithPickerQuery(), new TableResultControl(), new LookupFieldWithPickerEntityEditor())
		{
		}

		protected override void OnLoad(EventArgs e)
		{
			var tableResultControl = (TableResultControl) ResultControl;

			var columnDisplayNames = tableResultControl.ColumnDisplayNames;
			columnDisplayNames.Clear();

			var columnNames = tableResultControl.ColumnNames;
			columnNames.Clear();

			var columnWidths = tableResultControl.ColumnWidths;
			columnWidths.Clear();

			var propertyBag = new LookupFieldWithPickerPropertyBag(CustomProperty);

			using (var web = SPContext.Current.Site.OpenWeb(propertyBag.WebId))
			{
				var list = web.Lists[propertyBag.ListId];

				foreach (SPField field in list.Fields)
				{
					if (!propertyBag.SearchFields.Contains(field.InternalName) && propertyBag.FieldId != field.Id)
						continue;

					columnDisplayNames.Add(field.Title);
					columnNames.Add(field.Id.ToString());
				}
			}

			if (columnNames.Count > 0)
			{
				var width = 100/columnNames.Count;

				for (var i = 0; i < columnNames.Count; i++)
				{
					columnWidths.Add(width.ToString() + "%");
				}
			}

			base.OnLoad(e);

			;
		}
	}
}